<?php
/**
 * Kolekcia SQL resultov
 * implements Iterator
 * @author Tomas Srna
 * @package bakalarka
 */

class Collection implements Iterator
{
	private $position = 0;
	private $data = array();
	private $selector = NULL;
	
	/**
	 * V kontruktore nacitame data
	 * @param Selector $sel		Selector
	 */
	public function __construct(Selector $sel)
	{
		$this->selector = $sel;
		
		$r = $sel->db()->query($sel);
		
		if($sel->fetch_class() != "")
		{
			$this->data = $r->fetchAll(PDO::FETCH_CLASS, $sel->fetch_class());
			foreach($this->data as $item)
				$item->consolidate();
		}
		else
		{
			$this->data = $r->fetchAll(PDO::FETCH_OBJ);
		}
	}
	
	/**
	 * Vypis polozky (implicitne aktualnej)
	 * @param bool $return		Mame to vratit miesto vypisu?
	 * @param int $v			Ktory objekt (implicitne aktualna)
	 */
	public function write($return = false, $v = NULL)
	{
		if($v === NULL)
		{
			$v = $this->current();
		}
		
		$r = "";
		$r .= "(";
		$r .= get_class($v);
		
		if($this->selector->fetch_class() == "")
		{
			$vars = get_object_vars($v);
			foreach ($vars as $var => $val)
				$r .= "; $var: '$val'";
		}
		else if($v instanceof Model)
		{
			foreach($v->fields() as $f)
			{
				$r .= "; {$f->name}: '{$v->{$f->name}}'";
			}
		}
		
		$r .= ")";
		
		if($return)
			return $r;
		else
			echo $r;
	}
	
	/**
	 * Dump dat
	 * @param bool $return 		Mame to vratit miesto vypisu?
	 */
	public function dump($return = false)
	{
		$r = "";
		$r .= "[";
		
		if(count($this->data) > 0)
		{
			foreach($this->data as $v)
			{
				$r .= "\n" . $this->write(true, $v);
			}
			$r .= "\n";
		}
		
		$r .= "]";
		
		if($return)
			return $r;
		else
			echo $r;
	}
	
	// -------- Implementacia interfacu Iterator
	
	public function rewind()
	{
		$this->position = 0;
	}
	
	public function current()
	{
		return $this->data[$this->position];
	}
	
	public function key()
	{
		return $this->position;
	}
	
	public function next()
	{
		++$this->position;
	}
	
	function valid()
	{
		return isset($this->data[$this->position]);
	}
}
